﻿/*----------------------------------------------------------
 *  创建者：wangjj
 *  创建时间：2019-8-19 11:57:02
 *  功能描述：网络请求帮助类
 *  
 *  更新历史：
 ----------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using static minidwm.HttpModel;

namespace minidwm
{
    /// <summary>
    /// 网络请求帮助类
    /// </summary>
    public class HttpHepler
    {
        #region 预定义方变量  
        /// <summary>
        /// 默认的编码 
        /// </summary>
        private Encoding encoding = Encoding.Default;
        /// <summary>
        /// Post数据编码
        /// </summary>
        private Encoding postencoding = Encoding.Default;
        /// <summary>
        /// HttpWebRequest对象用来发起请求 
        /// </summary>
        private HttpWebRequest request = null;
        /// <summary>
        /// 获取影响流的数据对象
        /// </summary>
        private HttpWebResponse response = null;
        /// <summary>
        /// 设置本地的出口ip和端口
        /// </summary>
        private IPEndPoint iPAndPoint = null;
        #endregion

        #region Public

        /// <summary>
        /// 根据相传入的数据，得到相应页面数据
        /// </summary>
        /// <param name="item">参数类对象</param>
        /// <returns>返回HttpResult类型</returns>
        public HttpResult GetHtml(HttpItem item)
        {
            //返回参数
            HttpResult result = new HttpResult();
            try
            {
                //准备参数
                SetRequest(item);
            }
            catch (Exception ex)
            {
                //配置参数时出错
                return new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错：" + ex.Message };
            }
            try
            {
                //请求数据
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    GetData(item, result);
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (response = (HttpWebResponse)ex.Response)
                    {
                        GetData(item, result);
                    }
                }
                else
                {
                    result.Html = ex.Message;
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            if (item.IsToLower) result.Html = result.Html.ToLower();
            //重置request，response为空
            if (item.IsReset)
            {
                request = null;
                response = null;
            }
            return result;
        }

        #region 匹配页面的图片地址

        public List<ImgItem> GetImgList(string url)
        {
            List<ImgItem> imgItems = new List<ImgItem>();

            //创建Httphelper参数对象
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项        
            };
            //请求的返回值对象
            HttpResult result = this.GetHtml(item);
            if (result.StatusCode == HttpStatusCode.OK)
            {
                string Reg = @"<img.+?>";
                foreach (Match m in Regex.Matches(result.Html.ToLower(), Reg))
                {
                    imgItems.Add(new ImgItem
                    {
                        Html = m.Value,
                        Src = GetImgSrc((m.Value).ToLower().Trim(), url)
                    });
                }
            }
            return imgItems;
        }

        /// <summary>
        /// 匹配页面的图片地址
        /// </summary>
        /// <param name="imgHttp">要补充的http://路径信息</param>
        public string GetImgSrc(string HtmlCode, string imgHttp)
        {
            string MatchVale = "";
            string Reg = @"<img.+?>";
            foreach (Match m in Regex.Matches(HtmlCode.ToLower().Replace("\\", ""), Reg))
            {
                MatchVale += GetImg((m.Value).ToLower().Trim(), imgHttp);
            }

            return MatchVale;
        }

        /// <summary>
        /// 匹配<img src="" />中的图片路径实际链接
        /// </summary>
        /// <param name="ImgString"><img src="" />字符串</param>
        private string GetImg(string ImgString, string imgHttp)
        {
            string MatchVale = "";
            string Reg = @"src=.+\.(bmp|jpg|gif|png|)";
            foreach (Match m in Regex.Matches(ImgString.ToLower().Replace("\\", ""), Reg))
            {
                MatchVale += (m.Value).ToLower().Trim().Replace("src=", "").Replace(@"\", "");
            }
            if (MatchVale.IndexOf(".net") != -1 || MatchVale.IndexOf(".com") != -1 || MatchVale.IndexOf(".org") != -1 || MatchVale.IndexOf(".cn") != -1 || MatchVale.IndexOf(".cc") != -1 || MatchVale.IndexOf(".info") != -1 || MatchVale.IndexOf(".biz") != -1 || MatchVale.IndexOf(".tv") != -1)
                return (MatchVale.Replace("\"", ""));
            else
                return (imgHttp + MatchVale.Replace("\"", ""));
        }

        #endregion

        /// <summary>
        /// 过滤html标签
        /// </summary>
        /// <param name="strHtml">html的内容</param>
        /// <returns>返回过滤的string内容</returns>
        public static string StripHTML(string htmlStr)
        {
            string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
            string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
            string regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式 
            htmlStr = Regex.Replace(htmlStr, regEx_style, "", RegexOptions.IgnoreCase | RegexOptions.Compiled);//删除css
            htmlStr = Regex.Replace(htmlStr, regEx_script, "", RegexOptions.IgnoreCase | RegexOptions.Compiled);//删除js
            htmlStr = Regex.Replace(htmlStr, regEx_html, "", RegexOptions.IgnoreCase | RegexOptions.Compiled);//删除html标记
            htmlStr = Regex.Replace(htmlStr, "/n", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);//去除/n
            htmlStr = Regex.Replace(htmlStr, "&(quot|#34)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);//去除nbsp
            htmlStr = Regex.Replace(htmlStr, "&(amp|#38)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(lt|#60)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(gt|#62)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(nbsp;|#160)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(nbsp|#160)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(iexcl|#161)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(cent|#162)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(pound|#163)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = Regex.Replace(htmlStr, "&(copy|#169)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            htmlStr = htmlStr.Trim();
            return htmlStr;
        }

        /// <summary>
        /// 设置URl格式(Decode)解码
        /// </summary>
        /// <param name="text">内容</param>
        /// <returns>返回格式好的地址</returns>
        //public static string URLDecode(string text)
        //{
        //    return System.Web.HttpUtility.UrlDecode(text, Encoding.Default);
        //}

        /// <summary>
        /// 设置URl格式(Encode)转码
        /// </summary>
        /// <param name="text">内容</param>
        /// <returns>返回格式好的地址</returns>
        //public static string URLEncode(string text)
        //{
        //    return System.Web.HttpUtility.UrlEncode(text, Encoding.Default);
        //}

        #endregion

        #region GetData

        /// <summary>
        /// 获取数据的并解析的方法
        /// </summary>
        /// <param name="item"></param>
        /// <param name="result"></param>
        private void GetData(HttpItem item, HttpResult result)
        {
            if (response == null)
            {
                return;
            }
            #region base
            //获取StatusCode
            result.StatusCode = response.StatusCode;
            //获取StatusDescription
            result.StatusDescription = response.StatusDescription;
            //获取Headers
            result.Header = response.Headers;
            //获取最后访问的URl
            result.ResponseUri = response.ResponseUri.ToString();
            //获取CookieCollection
            if (response.Cookies != null) result.CookieCollection = response.Cookies;
            //获取set-cookie
            if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
            #endregion

            #region byte

            //处理网页Byte
            byte[] ResponseByte = GetByte();

            #endregion

            #region Html
            if (ResponseByte != null && ResponseByte.Length > 0)
            {
                //设置编码
                SetEncoding(item, result, ResponseByte);
                //得到返回的HTML
                result.Html = encoding.GetString(ResponseByte);
            }
            else
            {
                //没有返回任何Html代码
                result.Html = string.Empty;
            }
            #endregion
        }
        /// <summary>
        /// 设置编码
        /// </summary>
        /// <param name="item">HttpItem</param>
        /// <param name="result">HttpResult</param>
        /// <param name="ResponseByte">byte[]</param>
        private void SetEncoding(HttpItem item, HttpResult result, byte[] ResponseByte)
        {
            //是否返回Byte类型数据
            if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
            //从这里开始我们要无视编码了
            if (encoding == null)
            {
                Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta[^<]*charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                string c = string.Empty;
                if (meta != null && meta.Groups.Count > 0)
                {
                    c = meta.Groups[1].Value.ToLower().Trim();
                }
                if (c.Length > 2)
                {
                    try
                    {
                        encoding = Encoding.GetEncoding(c.Replace("\"", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
                    }
                    catch
                    {
                        if (string.IsNullOrEmpty(response.CharacterSet))
                        {
                            encoding = Encoding.UTF8;
                        }
                        else
                        {
                            encoding = Encoding.GetEncoding(response.CharacterSet);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(response.CharacterSet))
                    {
                        encoding = Encoding.UTF8;
                    }
                    else
                    {
                        encoding = Encoding.GetEncoding(response.CharacterSet);
                    }
                }
            }
        }
        /// <summary>
        /// 提取网页Byte
        /// </summary>
        /// <returns></returns>
        private byte[] GetByte()
        {
            byte[] ResponseByte = null;
            using (MemoryStream _stream = new MemoryStream())
            {
                //GZIIP处理
                if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                {
                    //开始读取流并设置编码方式
                    new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 1024);
                }
                else
                {
                    //开始读取流并设置编码方式
                    response.GetResponseStream().CopyTo(_stream, 1024);
                }
                //获取Byte
                ResponseByte = _stream.ToArray();
            }
            return ResponseByte;
        }

        #endregion

        #region SetRequest

        /// <summary>
        /// 为请求准备参数
        /// </summary>
        ///<param name="item">参数列表</param>
        private void SetRequest(HttpItem item)
        {

            // 验证证书
            SetCer(item);
            if (item.IPEndPoint != null)
            {
                iPAndPoint = item.IPEndPoint;
                //设置本地的出口ip和端口
                request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
            }
            //设置Header参数
            if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
                {
                    request.Headers.Add(key, item.Header[key]);
                }
            // 设置代理
            SetProxy(item);
            if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
            request.ServicePoint.Expect100Continue = item.Expect100Continue;
            //请求方式Get或者Post
            request.Method = item.Method;
            request.Timeout = item.Timeout;
            request.KeepAlive = item.KeepAlive;
            request.ReadWriteTimeout = item.ReadWriteTimeout;
            if (!string.IsNullOrWhiteSpace(item.Host))
            {
                request.Host = item.Host;
            }
            if (item.IfModifiedSince != null) request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
            if (item.Date != null)
            {
                request.Date = Convert.ToDateTime(item.Date);
            }
            //Accept
            request.Accept = item.Accept;
            //ContentType返回类型
            request.ContentType = item.ContentType;
            //UserAgent客户端的访问类型，包括浏览器版本和操作系统信息
            request.UserAgent = item.UserAgent;
            // 编码
            encoding = item.Encoding;
            //设置安全凭证
            request.Credentials = item.ICredentials;
            //设置Cookie
            SetCookie(item);
            //来源地址
            request.Referer = item.Referer;
            //是否执行跳转功能
            request.AllowAutoRedirect = item.Allowautoredirect;
            if (item.MaximumAutomaticRedirections > 0)
            {
                request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
            }
            //设置Post数据
            SetPostData(item);
            //设置最大连接
            if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
        }
        /// <summary>
        /// 设置证书
        /// </summary>
        /// <param name="item"></param>
        private void SetCer(HttpItem item)
        {
            if (!string.IsNullOrWhiteSpace(item.CerPath))
            {
                //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                //初始化对像，并设置请求的URL地址
                request = (HttpWebRequest)WebRequest.Create(item.URL);
                SetCerList(item);
                //将证书添加到请求里
                request.ClientCertificates.Add(new X509Certificate(item.CerPath));
            }
            else
            {
                //初始化对像，并设置请求的URL地址
                request = (HttpWebRequest)WebRequest.Create(item.URL);
                SetCerList(item);
            }
        }
        /// <summary>
        /// 设置多个证书
        /// </summary>
        /// <param name="item"></param>
        private void SetCerList(HttpItem item)
        {
            if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
            {
                foreach (X509Certificate c in item.ClentCertificates)
                {
                    request.ClientCertificates.Add(c);
                }
            }
        }
        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="item">Http参数</param>
        private void SetCookie(HttpItem item)
        {
            if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
            //设置CookieCollection
            if (item.ResultCookieType == ResultCookieType.CookieCollection)
            {
                request.CookieContainer = new CookieContainer();
                if (item.CookieCollection != null && item.CookieCollection.Count > 0)
                {
                    //默认为20个，如果超出需要增加长度
                    if (item.CookieCollection.Count > 20)
                    {
                        request.CookieContainer.PerDomainCapacity = item.CookieCollection.Count;
                    }
                    request.CookieContainer.Add(item.CookieCollection);
                }
            }
        }
        /// <summary>
        /// 设置Post数据
        /// </summary>
        /// <param name="item">Http参数</param>
        private void SetPostData(HttpItem item)
        {
            //验证在得到结果时是否有传入数据
            if (!request.Method.Trim().ToLower().Contains("get"))
            {
                if (item.PostEncoding != null)
                {
                    postencoding = item.PostEncoding;
                }
                byte[] buffer = null;
                //写入Byte类型
                if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
                {
                    //验证在得到结果时是否有传入数据
                    buffer = item.PostdataByte;
                }//写入文件
                else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata))
                {
                    StreamReader r = new StreamReader(item.Postdata, postencoding);
                    buffer = postencoding.GetBytes(r.ReadToEnd());
                    r.Close();
                } //写入字符串
                else if (!string.IsNullOrWhiteSpace(item.Postdata))
                {
                    buffer = postencoding.GetBytes(item.Postdata);
                }
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
                else
                {
                    request.ContentLength = 0;
                }
            }
        }
        /// <summary>
        /// 设置代理
        /// </summary>
        /// <param name="item">参数对象</param>
        private void SetProxy(HttpItem item)
        {
            bool isIeProxy = false;
            if (!string.IsNullOrWhiteSpace(item.ProxyIp))
            {
                isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
            }
            if (!string.IsNullOrWhiteSpace(item.ProxyIp) && !isIeProxy)
            {
                //设置代理服务器
                if (item.ProxyIp.Contains(":"))
                {
                    string[] plist = item.ProxyIp.Split(':');
                    WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
                    //建议连接
                    myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
                    //给当前请求对象
                    request.Proxy = myProxy;
                }
                else
                {
                    WebProxy myProxy = new WebProxy(item.ProxyIp, false);
                    //建议连接
                    myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
                    //给当前请求对象
                    request.Proxy = myProxy;
                }
            }
            else if (isIeProxy)
            {
                //设置为IE代理
            }
            else
            {
                request.Proxy = item.WebProxy;
            }
        }

        #endregion

        #region private main
        /// <summary>
        /// 回调验证证书问题
        /// </summary>
        /// <param name="sender">流对象</param>
        /// <param name="certificate">证书</param>
        /// <param name="chain">X509Chain</param>
        /// <param name="errors">SslPolicyErrors</param>
        /// <returns>bool</returns>
        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }

        /// <summary>
        /// 通过设置这个属性，可以在发出连接的时候绑定客户端发出连接所使用的IP地址。 
        /// </summary>
        /// <param name="servicePoint"></param>
        /// <param name="remoteEndPoint"></param>
        /// <param name="retryCount"></param>
        /// <returns></returns>
        private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
        {
            return iPAndPoint;//端口号
        }

        /// <summary>
        /// 字节数组生成图片
        /// </summary>
        /// <param name="Bytes">字节数组</param>
        /// <returns>图片</returns>
        private Image byteArrayToImage(byte[] Bytes)
        {
            MemoryStream ms = new MemoryStream(Bytes);
            Image outputImg = Image.FromStream(ms);
            return outputImg;
        }
        #endregion

        /// <summary>
        /// 获取网页内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url, Encoding encoding)
        {
            if (encoding == null)
                encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0";
                request.Accept = "*/*";
                request.Method = "GET";
                request.KeepAlive = true;
                request.Headers.Add("sec-ch-ua-platform", "Windows");
                request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
                request.Headers.Add("Accept-Encoding", "gzip, deflate, br, zstd");
                request.Headers.Add("Cookie", "BDqhfp=%E9%BA%BB%E8%B1%86%E4%BC%A0%E5%AA%92%26%260-10-1undefined%26%260%26%261; BIDUPSID=B8C2377F92F299B1EF5FA8FE5D70340F; BAIDUID=B8C2377F92F299B1D57F7A898BB8C0BB:FG=1; firstShowTip=1; cleanHistoryStatus=0; PSTM=1655967162; H_PS_PSSID=36559_36461_36673_36454_31254_36167_36570_36075_36654_26350_36468_22160; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BA_HECTOR=a52hal0h81ah052l001hb83mt14; ZFY=d2Em58DR2x29WgnTBSwbB5NMB9Lu89RDV1abRyEfdmM:C; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; userFrom=null; BDRCVFR[X_XKQks0S63]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; BAIDUID_BFESS=FD2A36E4F73D766F18C8493A9A0C9405:FG=1; indexPageSugList=%5B%22%E5%8E%A8%E5%B8%88%22%2C%22%E7%9A%84%22%2C%22%E9%BA%BB%E8%B1%86%E4%BC%A0%E5%AA%92%22%5D; BDUSS=k3RndtQ1pPZzlWRUJ4UlFleUNzLUdkRW9ZNUt-T3pDdTRPZFFHVlRPRkVuZHRpRVFBQUFBJCQAAAAAAAAAAAEAAAC24AX0cXEzNDc0OTY5MzQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEQQtGJEELRiMz; BDUSS_BFESS=k3RndtQ1pPZzlWRUJ4UlFleUNzLUdkRW9ZNUt-T3pDdTRPZFFHVlRPRkVuZHRpRVFBQUFBJCQAAAAAAAAAAAEAAAC24AX0cXEzNDc0OTY5MzQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEQQtGJEELRiMz; ab_sr=1.0.1_M2M3YjliZjE3NWU5MTJjMmVkYjE1Y2I4MjI2YjZiNjUxMTYzMzZiNDU1YzQzYzkyNjhhYjExNzUzZWU4ZGI0Y2NiOTdjMmI5ODdkOTMwNDlhYTliODNjMTA3MTVmMmY5ZjBmNDA5MmVlNzhiYjM1NWE1ZWQwZTM2MjBhZjMyZjEwZDM1MWEwYzU4MWE2MWQ5NmU0NjIyNjA0ZDIzM2IxNw==");
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
                {
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding);
                    else
                        reader = new StreamReader(response.GetResponseStream(), encoding);
                    string html = reader.ReadToEnd();
                    return html;
                }
            }
            catch
            {
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (reader != null)
                    reader.Close();
                if (request != null)
                    request = null;
            }
            return string.Empty;
        }
    }
}
